package com.cbl.v.ssczs.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cbl.v.ssczs.R;
import com.cbl.v.ssczs.mode.util.ActivityGroup;
import com.cbl.v.ssczs.mode.util.NetStatusUtil;
import com.cbl.v.ssczs.view.agent.OnPageListener;
import com.mingle.widget.ShapeLoadingDialog;

import static com.cbl.v.ssczs.MyApplication.getContext;

/**
 * 上海快三
 */
public class NavActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Toolbar toolbar;
    private DrawerLayout drawer;
    private ActionBarDrawerToggle toggle;
    private NavigationView navigationView;
    private WebView mWebView;
    private TextView mBtnShare;
    OnPageListener onPageListener;
    private ImageView title_back;
    private String webUrl;
    private SwipeRefreshLayout mSwipeRefresh;
    private LinearLayout mNoNetLayout, layout;
    private ShapeLoadingDialog shapeLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nav);
        initToolBar();
        initView();
        initRefresh();
        initListener();
    }


    private void initListener() {
        setOnPageListener(new OnPageListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onError() {
                if (!NetStatusUtil.isConnected(getContext())) {
                    shapeLoadingDialog.dismiss();
                    mNoNetLayout.setVisibility(View.VISIBLE);
                }
            }
        });

    }

    private void initView() {
        shapeLoadingDialog = new ShapeLoadingDialog(NavActivity.this);
        mBtnShare = (TextView) findViewById(R.id.btn_share);
        mWebView = (WebView) findViewById(R.id.web);
        initWebView(mWebView);
        //        webUrl = "https://video.1398t.com/pk10/h5shipin/?app=1";
        //        webUrl = "https://ic.snssdk.com/vertical/caipiao/report/";
        webUrl = "http://m.500.com/info/kaijiang/shhk3/170919032.shtml";
        mWebView.loadUrl(webUrl);
    }

    private void initToolBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("上海快3快三");
        setSupportActionBar(toolbar);
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    private long lastBackPress;

    @Override
    public void onBackPressed() {
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if (mWebView.canGoBack()) {
                if (mWebView.getUrl().equals(webUrl)) {
                    super.onBackPressed();
                } else {
                    if (mWebView != null) {
                        toolbar.setTitle("上海快3快三");
                        mWebView.goBack();
                    }

                }
            } else {
                if (System.currentTimeMillis() - lastBackPress < 1000) {
                    ActivityGroup.finishAllActivity();
                    System.exit(0);
                    super.onBackPressed();
                } else {
                    lastBackPress = System.currentTimeMillis();
                    Toast.makeText(NavActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_camera) {
            if (mWebView != null) {//上海快三
                mWebView.loadUrl("http://m.500.com/info/kaijiang/shhk3/170919032.shtml");
            } else {
                initWebView(mWebView);
                mWebView.loadUrl("http://m.500.com/info/kaijiang/shhk3/170919032.shtml");
            }
        } else if (id == R.id.nav_gallery) {//上海时时乐
            if (mWebView != null) {
                mWebView.loadUrl("http://m.500.com/info/kaijiang/ssl/20170919-08.shtml");
            } else {
                initWebView(mWebView);
                mWebView.loadUrl("http://m.500.com/info/kaijiang/ssl/20170919-08.shtml");
            }

        } else if (id == R.id.nav_slideshow) {
            if (mWebView != null) {
                //                mWebView.loadUrl("https://ic.snssdk.com/vertical/caipiao/report/");
                mWebView.loadUrl("http://m.500.com/info/kaijiang/bjsyxw/17091910.shtml");
            } else {
                initWebView(mWebView);
                mWebView.loadUrl("http://m.500.com/info/kaijiang/bjsyxw/17091910.shtml");
            }
        } else if (id == R.id.nav_slideshow1) {
            if (mWebView != null) {
                //                mWebView.loadUrl("https://ic.snssdk.com/vertical/caipiao/report/");
                mWebView.loadUrl("http://m.500.com/info/kaijiang/shhsyxw/170919-32.shtml");
            } else {
                initWebView(mWebView);
                mWebView.loadUrl("http://m.500.com/info/kaijiang/shhsyxw/170919-32.shtml");
            }
        } else if (id == R.id.nav_manage) {
            if (mWebView != null) {
                mWebView.loadUrl("http://m.500.com/info/kaijiang/bjkzhc/17091907.shtml");
            } else {
                initWebView(mWebView);
                mWebView.loadUrl("http://m.500.com/info/kaijiang/bjkzhc/17091907.shtml");
            }

        } else if (id == R.id.nav_share) {
            if (mWebView != null) {
                mWebView.loadUrl("https://m.qmcai.com/zixun/index.html");
            } else {
                initWebView(mWebView);
                mWebView.loadUrl("https://m.qmcai.com/zixun/index.html");
            }
        } else if (id == R.id.nav_send) {
            Intent intent = new Intent();
            intent.setClass(this, com.cbl.v.ssczs.view.activity.AGActivity.class);
            startActivity(intent);
//            if (mWebView != null) {
//                mWebView.loadUrl("https://m.qmcai.com/hd/caipiaoclass/index.html?newWebview=false&backH5Control=false&h5ControlTitle=false&version=5.2.16&channel=980");
//            } else {
//                initWebView(mWebView);
//                mWebView.loadUrl("https://m.qmcai.com/hd/caipiaoclass/index.html?newWebview=false&backH5Control=false&h5ControlTitle=false&version=5.2.16&channel=980");
//            }
        } else if (id == R.id.nav_about) {

            Intent intent = new Intent();
            intent.setClass(this, com.cbl.v.ssczs.view.activity.AboutUsActivity.class);
            startActivity(intent);
        }
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void initRefresh() {
        mNoNetLayout = (LinearLayout) findViewById(R.id.linearLayout_no_net);
        if (!NetStatusUtil.isConnected(this)) {
            mNoNetLayout.setVisibility(View.VISIBLE);
        } else {
            mNoNetLayout.setVisibility(View.GONE);
        }
        mSwipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh);
        //设置刷新时动画的颜色，可以设置4个
        mSwipeRefresh.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
                android.R.color.holo_orange_light, android.R.color.holo_green_light);
        mSwipeRefresh.setProgressViewOffset(false, 100, 200);
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!NetStatusUtil.isConnected(getContext())) {
                                    mNoNetLayout.setVisibility(View.VISIBLE);
                                    Toast.makeText(NavActivity.this, "无网络", Toast.LENGTH_SHORT).show();
                                } else {
                                    mNoNetLayout.setVisibility(View.GONE);
                                    mWebView.reload();
                                }

                                mSwipeRefresh.setRefreshing(false);
                            }
                        });
                    }
                }).start();
            }
        });
    }

    public void initWebView(WebView mWebView) {
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportMultipleWindows(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setSavePassword(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setUseWideViewPort(true);

        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                //判断标题 title 中是否包含有“error”字段，如果包含“error”字段，则设置加载失败，显示加载失败的视图
                if (!TextUtils.isEmpty(title) && title.toLowerCase().contains("无法打开")) {
                    onPageListener.onError();
                }
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.i("TAG", url);
                if (url == null) return false;
                if (url.length() > 20 && url.substring(0, 17).equals("sslocal://webview")) {
                    try {
                        String str1 = url.substring(url.lastIndexOf("%") + 1, url.indexOf("&"));
                        view.loadUrl("https://i.snssdk.com/vertical/caipiao/detail/?caipiao_id=" + str1.substring(2,
                                str1.length()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
                try {
                    if (url.startsWith("qmcai://")) {
                        if (url.endsWith("jczdg") ||
                                url.endsWith("bjdc") ||
                                url.endsWith("jcz") ||
                                url.endsWith("BasketBallActivity")) {
                            Toast.makeText(NavActivity.this, "　　请严格遵守法律法规！\n" +
                                    "请到附近的实体店以现金购买！\n" +
                                    "谢谢您的支持！祝您好运哦 ！", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(NavActivity.this, "此功能将在下一个版本开放！", Toast.LENGTH_SHORT).show();
                        }
                        return true;
                    }
                } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                try {
                    if (url.equals("http://m.500.com/info/kaijiang/shhk3/170919032.shtml")) {
                        toolbar.setTitle("上海快三开奖");
                    }
                    if (url.equals("http://m.500.com/info/kaijiang/ssl/20170919-08.shtml")) {
                        toolbar.setTitle("上海时时乐开奖");
                    }
                    if (url.equals("http://m.500.com/info/kaijiang/shhsyxw/170919-32.shtml")) {
                        toolbar.setTitle("上海11选5开奖");
                    }
                    if (url.equals("http://m.500.com/info/kaijiang/bjsyxw/17091910.shtml")) {
                        toolbar.setTitle("北京11选5开奖");
                    }
                    if (url.equals("http://m.500.com/info/kaijiang/bjkzhc/17091907.shtml")) {
                        toolbar.setTitle("北京快中彩开奖");
                    }
                    if (url.equals("https://m.qmcai.com/zixun/index.html")) {
                        toolbar.setTitle("竞彩新闻资讯");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                shapeLoadingDialog.setLoadingText("加载中...");
                shapeLoadingDialog.show();
                onPageListener.onError();

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (!NetStatusUtil.isConnected(getContext())) {
                    mNoNetLayout.setVisibility(View.VISIBLE);
                } else {
                    mNoNetLayout.setVisibility(View.GONE);
                }
                shapeLoadingDialog.dismiss();
            }

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                onPageListener.onError();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
    }

    public void setOnPageListener(OnPageListener onPageListener) {
        this.onPageListener = onPageListener;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mWebView != null) {
            mWebView.reload();
        }
    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
        super.onDestroy();
    }
}
